import express from "express";
import config from "../config/const";
// 引入mock
import mocks from "../../renderer/mock/index";
import {lowerCase} from "lodash";

const app = express();
const router = express.Router();

const BaseApi = process.env.REMOTE_API ?? config.RemoteApi;

/**
 * 解决跨域
 */
const cors = (req, res, next) => {
	//设置允许跨域的域名，*代表允许任意域名跨域
	res.header("Access-Control-Allow-Origin", "*");
	//允许的header类型
	res.header("Access-Control-Allow-Headers", "*");
	res.header("Access-Control-Allow-Credentials", true);
	//跨域允许的请求方式
	res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
	res.header("Content-Type", "application/json;charset=utf-8");

	if (req.method.toLowerCase() === "options")
		res.sendStatus(200); //让options尝试请求快速结束
	else next();
};

//添加空路由占位符,后期动态添加路由用
// const arr = ["GET","POST","DELETE","PUT","HEAD","OPTIONS"];
// arr.some((method)=>{
//   let m = lowerCase(method);
//     router[m]("/*", (req,res,next)=>{
//       next();
//     })
// });

//示范
app.get("/message", (req, res) => {
	res.send("这是来自node服务端的信息");
});

app.post("/message", (req, res) => {
	if (req) {
		res.send(req + "--来自node");
	}
});

for (let i in mocks) {
	let mocker = mocks[i];
	mocker.forEach((mock) => {
		// console.log(BaseApi+mock.url);
		let api = BaseApi + mock.url;
		let callback = function (req, res) {
			// console.log(req.params);
			//{userId:'2'}
			if (Object.keys(req.params).length > 0) {
				// console.log(mock.body)
				let data = mock.body({params: req.params});
				// console.log(data)
				res.send(data);
			} else {
				let data = mock.body;
				res.send(data);
			}
		};
		/**
		 * 请求类型 ["GET","POST","DELETE","PUT","HEAD","OPTIONS",……];
		 */
		let methods = mock.method;
		methods.some((method) => {
			let m = lowerCase(method);
			router[m](api, callback);
		});
	});
}
app.use("/", cors, router);
export default app;
